Practice Problems on Functions in C++

Posted on December 18, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Basic Practice Problems based on chapter which you learn in previous Tutorials.

1. Sum of Natural Number using Recursion in C++

#include <iostream>Copy Code
int main() {
// Declare variables to store the two numbers
double num1, num2;

// Input the two numbers
std::cout << "Enter the first number: ";
std::cin >> num1;

std::cout << "Enter the second number: ";
std::cin >> num2;

// Perform addition
double sum = num1 + num2;

// Display the result
std::cout << "Sum: " << sum << std::endl;

return 0;
}

2. Prime Numbers using Functions

#include <iostream>Copy Code
#include <iostream>
#include <cmath>

// Function to check if a number is prime
bool isPrime(int n) {
if (n <= 1) {
return false;
}

for (int i = 2; i <= sqrt(n); ++i) {
if (n % i == 0) {
return false;
}
}

return true;
}

int main() {
// Declare a variable to store the number
int number;

// Input the number
std::cout << "Enter an integer: ";
std::cin >> number;

// Check if the number is prime using the isPrime function
if (isPrime(number)) {
std::cout << number << " is a prime number." << std::endl;
} else {
std::cout << number << " is not a prime number." << std::endl;
}

return 0;
}

3. Greatest common Divisor(GCD) using Recursion

#include <iostream>Copy Code
// Recursive function to find the GCD
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}

int main() {
// Declare variables to store the two numbers
int num1, num2;

// Input the two numbers
std::cout << "Enter the first integer: ";
std::cin >> num1;

std::cout << "Enter the second integer: ";
std::cin >> num2;

// Check if the numbers are non-negative
if (num1 < 0 || num2 < 0) {
std::cout << "Please enter non-negative integers." << std::endl;
return 1;
}

// Calculate and display the GCD using the gcd function
int result = gcd(num1, num2);
std::cout << "GCD of " << num1 << " and " << num2 << " is: " << result << std::endl;

return 0;
}

The gcd function is defined to calculate the GCD using the Euclidean algorithm and recursion.

4. Octal to Decimal

#include <iostream>Copy Code
#include <iostream>
#include <cmath>

// Function to convert octal to decimal
int octalToDecimal(int octalNumber) {
while (octalNumber != 0) {
int remainder = octalNumber % 10;
decimalNumber += remainder * pow(8, i);
++i;
octalNumber /= 10;
}

return decimalNumber;
}

int main() {
// Declare a variable to store the octal number
int octalNumber;

// Input the octal number
std::cout << "Enter an octal number: ";
std::cin >> octalNumber;

// Check if the octal number is non-negative
if (octalNumber < 0) {
std::cout << "Please enter a non-negative octal number." << std::endl;
return 1;
}

// Convert and display the decimal equivalent
int decimalEquivalent = octalToDecimal(octalNumber);
std::cout << "Decimal equivalent: " << decimalEquivalent << std::endl;

return 0;
}